package com.demo.common.dynamic.datasource.utils;

import java.util.ArrayDeque;
import java.util.Deque;

/**
 * 数据源标识存储类
 *
 * @author molong
 * @date 2021/10/22
 */
public class DsContextHolder {
    private static final ThreadLocal<Deque<String>> CONTEXT_HOLDER = ThreadLocal.withInitial(ArrayDeque::new);

    private DsContextHolder() throws Exception {
        throw new InstantiationException("无法实例化");
    }

    /**
     * 设置当前线程数据源标识
     * @param dsKey 数据源唯一标识
     */
    public static void setCurrentDataSourceKey(String dsKey) {
        CONTEXT_HOLDER.get().push(dsKey);
    }

    /**
     * 获取当前线程数据源的标识
     * @return 结果
     */
    public static String getCurrentDataSourceKey() {
        return CONTEXT_HOLDER.get().peek();
    }

    /**
     * 清空当前线程数据源标识
     */
    public static void clearDataSourceKey() {
        Deque<String> deque = CONTEXT_HOLDER.get();
        deque.poll();
        if (deque.isEmpty()) {
            CONTEXT_HOLDER.remove();
        }
    }
}
